<template>
    <!-- 搜索 -->
    <div class="search">
        <label>
            根据姓名搜索
        </label>
        <el-select v-model="searchKey" filterable clearable remote placeholder="根据姓名搜索" :remote-method="remoteMethod"
            @change="searchchange" :loading="searchLoading">
            <el-option v-for="item in searchOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
    </div>
    <!-- 添加按钮 -->
    <div class="add">
        <el-button type="primary" :icon="Plus" @click="addStu" v-has:add="permission" :disabled="k">添加项目</el-button>
    </div>
    <div class="export">
        <el-button   @click="exportExcel">
            <template v-slot:icon>
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-excel"></use>
                  </svg>
                  </template>
                  <template #default>
                    导出Excel
                  </template>
        </el-button>
    </div>

    <!-- 带边框的表格 -->
    <el-table :data="tableData" border v-loading="tableloading">
        <el-table-column prop="headimgurl" label="头像">
            <template #default="scope">
                <div style="display: flex; align-items: center">
                    <el-avatar :src="scope.row.headimgurl"> user </el-avatar>
                </div>
            </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="degree" label="学历" align="center" />
        <el-table-column prop="class" label="班级" align="center" />
        <el-table-column prop="productUrl" label="项目" align="center" />
        <el-table-column prop="cTime" label="创建时间" align="center" />
        <el-table-column label="操作" align="center">
            <template v-slot="{ row }">
                <el-button type="success" :icon="View" circle @click="look"  v-has:read="permission"/>
                <el-button type="primary" :icon="Edit" @click="edit(row)" :disabled="k" circle v-has:edit="permission"/>
                <el-button type="danger" :icon="Delete" @click="del(row)" :disabled="k" circle v-has:delete="permission"/>
            </template>
        </el-table-column>
    </el-table>
    <!-- <分页> -->
    <div class="pageNation">
        <el-pagination background layout="prev, pager, next" @current-change="pageChange" :page-size="pageSize"
            :total="total" />
    </div>
    <!-- dialog弹窗组件 -->
    <qfdialog 
        @closed="close" 
        :dialogFormData="dialogFormData" 
        :title="dialogTitle"
        @validateSuccess="dialogFormValidateSuccess" 
        @dialogCancel="dialogCancel" 
        :visible="dialogVisible">
        <template v-slot:upload>
            <el-upload v-loading="uploading" method="post" class="avatar-uploader"
                action="/api/students/uploadStuAvatar" name="headimgurl" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
            </el-upload>
        </template>
    </qfdialog>

</template>
<script setup>
import { ElLoading, ElMessage, ElMessageBox } from "element-plus"
import { ref, reactive } from "vue"
import * as api from "../../../../api/students"
import { onMounted,} from "vue"
import { Delete, View, Edit, Plus } from '@element-plus/icons-vue'
// 引入dailog弹窗组件
import qfdialog from "../../../../components/dialog/index.vue"
import qee from "qf-export-excel"
import { useRouter } from "vue-router"
import {useUser} from "../../../../store/allstore"
import { storeToRefs } from "pinia"
let userStore=useUser()
let {permission}=storeToRefs(userStore)
console.log(permission.value)
let router=useRouter()
// 搜索逻辑
let searchKey = ref("")
// 搜索加载动画
let searchLoading = ref(false)
// 搜索数据结构
let searchOptions = ref([])
// 加载动画
let tableloading = ref(true)
// 表格数据
let tableData = ref([])
let imgData = ref([])
let getStulist = async (pageXOffset, count, classes) => {
    tableloading.value = true
    try {
        let res = await api.getStudentSpace(pageXOffset, count, classes)
        // 给联想的列表进行赋值
        tableData.value = res.data.data
        tableloading.value = false
        setPageNation(res.data.total)
    } catch (e) {
        console.log(e)
    }
}
// 搜索框输入之后会触发的方法，这里负责呈现搜索的联想数据
let remoteMethod = async (currentKeyWord) => {
    //打开表格的loading动画
    // console.log(key)
    try {
        // 要搜索全部的数据,所以传递空字符串count,默认全部搜索
        let res = await api.findStudent(currentKeyWord, "")
        let repeatDatas = res.data.data.map(item => ({ value: item.name }))
        // 要去重操作
        let norepeatDatas = []
        for (var i = 0; i < repeatDatas.length; i++) {

            // 声明一个开关
            let flag = true
            for (var j = 0; j < norepeatDatas.length; j++) {
                if (repeatDatas[i].value === norepeatDatas[j].value) {

                    flag = false
                    break
                }
            }
            if (flag) {
                norepeatDatas.push(repeatDatas[i])
            }
        }
        // 去重之后对Options进行赋值操作
        searchOptions.value = norepeatDatas
        tableloading.value = false
    } catch (e) {
        console.log(e)
    }
}

// // 用户选择了输入框的值之后，负责跟新表格数据
let searchchange = async (key, page = 1, count = 10) => {
    // 获取用户点选的值
    tableloading.value = true
    // 清空上一次获取到的值
    searchOptions.value = []
    try {
        let res = await api.findStudent(searchKey.value, count, page)
        // 对表格的数据操作,将搜索的结果赋值给表格
        tableData.value = res.data.data
        tableloading.value = false
        // 对搜索的结果进行分页
        setPageNation(res.data.total)

    } catch (e) {
        tableloading.value = false
        console.log(e)
    }
}

// 处理分页
// 分页器的total属性
let total = ref(1)
// 一页展示多少条
let pageSize = ref(10)
//页码变更的时候
let pageChange = (currentPage) => {
    // 判断有没有搜索关键字,如果有应该更新搜索的分页结果,不然才是拉去列表全部数据
    if (searchKey.value) {
        searchchange(null, currentPage)
    } else {
        getStulist(currentPage)
    }
}
// 专门修改分页器内容的方法
let setPageNation = (totalCount = 10, count = 10, currentPage = 1) => {
    total.value = totalCount
    pageSize.value = count
}

//添加stu信息
// dialog标题

let dialogTitle = ref('增加学员信息')
let dialogVisible = ref(false)
let addStu = () => {
    // 打开dialog
    dialogTitle.value = ('增加学员信息')
    dialogVisible.value = true

}

// dialog的数据源
let dialogFormData = reactive({
    class: {
        label: '班级',
        value: ""
    },
    name: {
        label: '姓名',
        value: ""
    },
    age: {
        label: '年龄',
        value: ""
    },
    city: {
        label: '城市',
        value: ""
    },
    degree: {
        label: '学历',
        value: ""
    },
    productUrl: {
        label: '项目地址',
        value: ""
    },
    description: {
        label: '描述',
        value: ""
    },

})

// dialog点击了确定按钮,并且表单校验通过触发的逻辑
let dialogFormValidateSuccess = async (form) => {
    let message = ref('')
    // 将输入的内容传递给服务器
    let parms = {
        class: dialogFormData.class.value,
        name: dialogFormData.name.value,
        age: dialogFormData.age.value,
        city: dialogFormData.city.value,
        degree: dialogFormData.degree.value,
        productUrl: dialogFormData.productUrl.value,
        description: dialogFormData.description.value,
        headimgurl: ""
    }
    try {
        let apiMethod = null
        switch (dialogTitle.value) {
            case '增加学员信息':
                apiMethod = api.addStudentSpace
                // 删除sId这条属性
                parms.sId ?? delete parms.sId
                break
            case "编辑信息":
                apiMethod = api.changeStudentSpace
                // 给params中添加sId属性
                parms.sId = sId.value
                // 更改提示信息
                message = '修改成功'
        }
        // 判断是否上传头像，如果上传了，携带到parms中去
        parms.headimgurl = headimgurl.value ? headimgurl.value : ""
        let res = await apiMethod(parms)
        // 添加成功之后
        // 1.提示添加成功
        ElMessage({
            type: 'success',
            message: '添加成功'
        })
        // 2.关掉dialog
        dialogVisible.value = false
        // 3.清空表单
        form.value.resetFields()
        // 4.跟新列表
        getStulist()

    } catch (e) {

        ElMessage({
            type: 'error',
            message: e.toString()
        })
        console.log(e)
    }
}

// 点击取消按钮触发的逻辑
let dialogCancel = () => {
    // dialogForm.resetFields()
    dialogVisible.value = false
}

// dialog关闭之后，要同步控制关闭属性的值
// 这么做是为了点击处理空白区域或者右上角叉叉的时候，造成的后续的ialog不能弹开的情况
let close = () => {
   
    // 将数据清空
    let keys = Object.keys(dialogFormData)
    keys.forEach(key => {
        dialogFormData[key].value = ""
    })
    // 清空头像的回显
    imageUrl.value = ""
    dialogVisible.value = false
}

// 编辑
// 声明一个遍历存储sId便于编辑的时候传递给后端
let sId = ref('')
let edit = (row) => {
    // 1.打开dialog
    dialogVisible.value = true
    // 2.修改标题
    dialogTitle.value = '编辑信息'
    // 3.数据需要回显
    let keys = Object.keys(dialogFormData)
    keys.forEach(key => {
        dialogFormData[key].value = row[key]
    })
    // 给sId赋值
    sId.value = row.sId
    // 更改全局的headimgurl这个字段便于数据的回显操作,便于数据的传递
    headimgurl.value = row.imageUrl
    // 回显
    imageUrl.value = row.headimgurl
}

// 删除
let del = (row) => {
    // 获取当前这条数据的id,传递给后台
    // 1.交互 让用户确定是否删除
    ElMessageBox.confirm('此操作将永久删除' + row.name + ',是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    })
        .then(async () => {
            try {
                let res = await api.deleteStudentSpace(row.sId)
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                })
                getStulist()
            } catch (e) {
                ElMessage({
                    type: 'error',
                    message: '删除失败'
                })
            }
        })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '已取消删除'
            })
        })
    // 2.发请求 删除数据
}


// 上传文件
// 保存上传地址的变量
let imageUrl = ref("")
// 声明一个headimgurl变量,用于将参数在表单dialog通过的时候一并提交给后台
let headimgurl = ref()
// 上次成功的方法
let handleAvatarSuccess = (res, uploadFile) => {
    // console.log(uploadFile.raw)
    // console.log(res)
    if (res.state) {
        console.log(res)
        ElMessage({
            type: 'success',
            message: res.msg
        })
        headimgurl.value = res.headimgurl
    } else {
        ElMessage({
            type: 'error',
            message: res.msg
        })
    }
    // 关闭加载动画
    uploading.value = false
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
}


// 加载动画
let uploading = ref(false)
// 上传之前
let beforeAvatarUpload = (rawFile) => {

    console.log(rawFile.type)
    // 允许上传的文件类型
    let acceptType = ['image/jpeg', 'image/png']
    // 判断当前上传的文件类型是否包含在上面的数组中
    let isAccept = acceptType.includes(rawFile.type)
    if (!isAccept) {
        ElMessage.error('上传的文件类型只能是png或者jpeg,您当前上传的文件类型是' + rawFile.type)
        return false
    } else if (rawFile.size / 1024 / 1024 > 1) {
        ElMessage.error('上传文件不能超过1M!')
        return false
    }
    // 打开加载动画
    uploading.value = true
    return true
}
onMounted(() => {
    getStulist()
})


// 导出Excel
let exportExcel=()=>{
    // 定义表头
    let litleSource=[
        {
            title:'姓名',
            key:'name'
        },
        {
            title:'年龄',
            key:'age'
        },
        {
            title:'头像地址',
            key:'headimgurl'
        },
        {
            title:'学历',
            key:'degree'
        },
        {
            title:'班级',
            key:'class'
        },
    ]
    qee(litleSource,tableData.value,'工资单')
}

</script>
<script>
export default {
    meta: {
        title: 'xyxmgl',
        name: '学员项目管理',
        icon: 'icon-xiangmu'
    }
}

let look=()=>{

}
let k =ref(false)
let vHas={
    mounted (el,binding) {
        console.log(el)
        console.log(binding)
        let haveper=binding.value
        let needper=binding.arg
        let g=binding.value.includes(binding.arg)
        console.log(g)
        if(!g){
            k=true
        }
    }
}
</script>
<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
